<template>
  <!-- 编辑和新增弹框 -->

  <el-dialog title="新增" :visible="dialogVisible" width="40%" @close="reset">
    <el-form
      ref="form"
      v-model="properties"
      label-position="left"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="properties.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="经纪人" prop="agent">
        <el-select v-model="properties.agent" placeholder="请选择">
          <el-option
            v-for="item in agentsList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="properties.content" placeholder="内容" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="properties.address" placeholder="地址" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="properties.price" placeholder="价格" />
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
          v-for="tag in properties.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          icon="el-icon-plus"
          plain
          @click="showInput"
        >
          新增标签</el-button>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="properties.category" placeholder="请选择">
          <el-option
            v-for="item in categoriesList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经纪头像">
        <el-upload
          action="#"
          :http-request="
            (params) => {
              imageLoadFn(params, portrait);
            }
          "
          list-type="picture-card"
          :file-list="portrait"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="住房图片">
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="imgArr"
          :http-request="
            (params) => {
              imageLoadFn(params, imgArr);
            }
          "
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button class="btn" type="text" @click="reset">取 消</el-button>
      <el-button
        type="primary"
        class="btn"
        style="margin-left: 40px"
        @click="addProperties"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 引入接口
import { addProperties } from '../../../api/properties'
// 引入js-sdk
import COS from 'cos-js-sdk-v5'

// 初始化COS对象
const cos = new COS({
  SecretId: 'AKIDDF1WkhNnwoQlpc8NL2ScV6QZPyGH2Wid',
  SecretKey: 'h7G7i13qMchZ9SUFjvrWtzoMcbJkumNl'
})

// cos.putObject({
//   Bucket: 'hr-79-1313468568', /* 必须 */
//   Region: 'COS_REGION', /* 存储桶所在地域，必须字段 */
//   Key: 'exampleobject', /* 必须 */
//   StorageClass: 'STANDARD',
//   Body: fileObject, // 上传文件对象
//   onProgress: function(progressData) {
//     console.log(JSON.stringify(progressData))
//   }
// }, function(err, data) {
//   console.log(err || data)
// })

import { getCategoriesList, getAgentsList } from '../../../api/properties'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      portrait: [], // 经纪公司头像
      imgArr: [], // 住房图片数组
      agentsList: [], // 经纪列表
      categoriesList: [], // 分类列表
      inputVisible: false,
      inputValue: '',

      properties: {
        title: '', // 标题
        desc: '', // 描述
        image: '', // 图片
        agent: 38, // 属于哪个经纪的 id 值
        content: '', // 内容
        address: '', // 地址
        price: '', // 价格
        photos: [], // 图片, url 组成数组
        tags: [], // 标签, 字符串组成数组
        category: 5 // 属于哪个分类 id 值
      },
      // 表单校验
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        desc: [{ required: true, message: '请填写', trigger: 'blur' }],
        agent: [{ required: true, message: '请选择经纪公司', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        category: [{ required: true, message: '请选择类别', trigger: 'blur' }]
      }
    }
  },
  async created() {
    // 获取分类列表
    const res = await getCategoriesList()
    // 将数据回填给分类列表
    this.categoriesList = res.data
    // 获取经纪列表
    const data = await getAgentsList()
    // 将数据回填给经纪列表
    this.agentsList = data.data
  },
  methods: {
    // 关闭并重置新增和编辑弹框
    reset() {
      this.$emit('update:dialogVisible', false)
    },
    // 标签事件
    handleClose(tag) {
      this.properties.tags.splice(this.properties.tags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.properties.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 标签事件结束

    // 头像上传事件开始
    // 图片上传
    imageLoadFn(data, arr) {
      // arr是用图片上传的file-list绑定的值
      cos.putObject(
        {
          Bucket: 'hr-79-1313468568' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() /* 必须 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: function(progressData) {
            console.log(JSON.stringify(progressData))
          }
        },
        function(err, data) {
          console.log(227, err || data)
          arr.push({
            url: 'http://' + data.Location
          })
        }
      )
    },
    // 头像上传事件结束

    // 新增房产
    async addProperties() {
      // 获取经纪公司头像
      this.properties.image = this.portrait[0].url
      // 获取房产照片组
      this.properties.photos = this.imgArr.map((item) => {
        return item.url
      })
      // 先校验表单，成功后发送请求
      this.$refs['form'].validate(async(valid) => {
        // 校验成功
        if (valid) {
          // 发送新增请求
          await addProperties(this.properties)
          // 校验失败
        } else {
          return false
        }
      })

      // 调用父组件事件，重新渲染
      this.$parent.getPropertiesList()
    }
  }
}
</script>

<style lang="scss">
.el-upload-list__item img.el-upload-list__item-thumbnail,
.el-upload-list__item-delete {
  display: block;
  width: 50px;
  height: 50px;
  object-fit: cover; //此属性使用最多
}
.el-upload {
  position: relative;
  width: 50px;
  height: 50px;
}
.el-icon-plus::before {
  position: absolute;
  top: 33%;
  bottom: 50%;
  transform: translate(-50%, -50%);
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 50px;
  height: 50px;
  overflow: hidden;
  background-color: #fff;
  /* border: 1px solid #c0ccda; */
  /* border-radius: 6px; */
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  margin: 0 8px 8px 0;
  display: inline-block;
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 50px;
  height: 50px;
  overflow: hidden;
  background-color: #fff;
  border: none;
  /* border: 1px solid #c0ccda; */
  /* border-radius: 6px; */
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  margin: 0 8px;
  display: inline-block;
  width: 50px;
  height: 50px;
}
</style>
